package com.company.woye.login;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.main.MainActivity;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.FileUtils;
import com.company.woye.utils.InstallUtils;
import com.company.woye.utils.NetWorkUtils;
import com.company.woye.utils.ParseXmlService;
import com.company.woye.utils.SharedPreferenceUtils;
import com.company.woye.utils.Toaster;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapFault;
import org.ksoap2.transport.HttpResponseException;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

import static com.company.woye.utils.FileUtils.getFilePath;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity {

    private static final String TAG = LoginActivity.class.getSimpleName();

    @BindView(R.id.ed_login_edtId)
    EditText edLoginEdtId;
    @BindView(R.id.ed_login_edtPwd)
    EditText edLoginEdtPwd;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.sw)
    ImageView aSwitch;

    boolean isShow=false;

    //升级更新部分start
    /* 保存解析的XML信息 */
    HashMap<String, String> ServerConfig;
    String SQLAddr = "", SQLUser = "", SQLPsw = "", SQLDBName = "";
    private static final int MSG_ERROR = 9000;
    private final static int MSG_CheckNetWork = 9004;
    //初始化定时器;
    private Timer netTimer;
    private TimerTask netTimeTask;
    //升级相关的
    HashMap<String, String> mHashMap;

    //服务器地址
    String serviceUrl = "";
    private MyApplication myApp;
    private JSONArray loginJSONArray;//用于接收登陆返回信息;
    private final static int MSG_LoginCheckOver = 9002;

    private static final int PROGRESS_MAX = 0X1;
    private static final int UPDATE = 0X2;

    private PopupWindow popupWindow;
    private TextView txt_update;
    private ProgressBar progress_update;
    private Button btn_update;
    private TextView txt_SoftVer2;
    private String apkpath;
    //下载的ID
    private String apkname;

    private ProgressDialog progressDialog;

    int contentLen = 0;//文件大小；
    String curLoginUser = "", curLoginUserNo, curLoginTime = "", curUserPower = "",Factory="",JobNosL="",JobNosR="",Bbm="",
            CjName="",DepartMentNo="",DepartMent="",LStationNos="",RStationNos="",PPlaceNo="",LooseClothRackNo="";
    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_LoginCheckOver:
                    try {
                        if (loginJSONArray != null) {
                            if (loginJSONArray.optJSONObject(0).getString("LoginCheck").equals("OK")) {
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo")) {
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                    myApp.curLoginUserNo = curLoginUserNo;
                                }
                                SharedPreferenceUtils.putData(sharedPreferences,"LoginUserNo",curLoginUserNo);

                                if (loginJSONArray.optJSONObject(0).has("JobNoL")){
                                    JobNosL = loginJSONArray.optJSONObject(0).get("JobNoL").toString();
                                    myApp.JobNosL = JobNosL;
                                }
                                if (loginJSONArray.optJSONObject(0).has("JobNoR")){
                                    JobNosR = loginJSONArray.optJSONObject(0).get("JobNoR").toString();
                                    myApp.JobNosR = JobNosR;
                                }
                                if (loginJSONArray.optJSONObject(0).has("Factory")) {
                                    Factory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                    myApp.Factory = Factory;
                                }
                                if (loginJSONArray.optJSONObject(0).has("Bbm")) {
                                    Bbm = loginJSONArray.optJSONObject(0).get("Bbm").toString();
                                    myApp.Bbm = Bbm;
                                }
                                if (loginJSONArray.optJSONObject(0).has("CjName")) {
                                    CjName = loginJSONArray.optJSONObject(0).get("CjName").toString();
                                    myApp.CjName = CjName;
                                }
                                if (loginJSONArray.optJSONObject(0).has("DepartMentNo")) {
                                    DepartMentNo = loginJSONArray.optJSONObject(0).get("DepartMentNo").toString();
                                    myApp.DepartMentNo = DepartMentNo;
                                }
                                if (loginJSONArray.optJSONObject(0).has("DepartMent")) {
                                    DepartMent = loginJSONArray.optJSONObject(0).get("DepartMent").toString();
                                    myApp.DepartMent = DepartMent;
                                }
                                if (loginJSONArray.optJSONObject(0).has("StationNoL")) {
                                    LStationNos = loginJSONArray.optJSONObject(0).get("StationNoL").toString();
                                    if (LStationNos.isEmpty()){
                                        Toaster.showLong(LoginActivity.this, "StationNoL为空无法登陆请注意！");
                                        //return;
                                    }
//                                    SharedPreferenceUtils.putData(sharedPreferences, "leftGongWei", LStationNos);
                                }
                                if (loginJSONArray.optJSONObject(0).has("StationNoR")) {
                                    RStationNos = loginJSONArray.optJSONObject(0).get("StationNoR").toString();
                                    if (RStationNos.isEmpty()){
                                        Toaster.showLong(LoginActivity.this, "StationNoR为空无法登陆请注意！");
                                        //return;
                                    }
//                                    SharedPreferenceUtils.putData(sharedPreferences, "rightGongWei", RStationNos);
                                }
                                if (loginJSONArray.optJSONObject(0).has("4PPlaceNo")) {
                                    PPlaceNo = loginJSONArray.optJSONObject(0).get("4PPlaceNo").toString();
                                    myApp.PPlaceNo = PPlaceNo;
                                }
                                if (loginJSONArray.optJSONObject(0).has("LooseClothRackNo")) {
                                    LooseClothRackNo = loginJSONArray.optJSONObject(0).get("LooseClothRackNo").toString();
                                    myApp.LooseClothRackNo = LooseClothRackNo;
                                }
                                if (loginJSONArray.optJSONObject(0).has("LoginUser")) {
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                    myApp.LoginUser = curLoginUser;
                                }
                                if (loginJSONArray.optJSONObject(0).has("LoginTime"))
                                    curLoginTime = loginJSONArray.optJSONObject(0).get("LoginTime").toString();
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                //登陆界面;
                                loginOK();
                            } else {
                                Toaster.showLong(LoginActivity.this, "请输入正确的账户跟密码");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_CheckNetWork:
                    System.out.println("EnterMSG_CheckNetWork");
                    boolean networkState = false;
                    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
                        networkState = NetWorkUtils.checkNetState_21(LoginActivity.this);
                    } else {
                        networkState = NetWorkUtils.checkNetState_21orNew(LoginActivity.this);
                    }
                    try {
                        if (networkState == true) {
                            stopCheckNetTimer();
                            Log.e(TAG, "serviceUrl" + serviceUrl);
                            if (!TextUtils.isEmpty(serviceUrl)){
                                CheckWebUpdate(serviceUrl + "/UPDATE/autolibary.xml");
                            }
                        } else {
                            Log.e(TAG, "-----------------------------------------CheckNetWork Err-----------------------------------------");
                        }
                    } catch (Exception e) {


                    }
                    break;
                case MSG_ERROR:
                    Toaster.showLong(LoginActivity.this, "连接数据库异常");
                    break;
            }
        }
    };
    //升级更新部分end


    @Override
    protected void onResume() {
        super.onResume();
        myApp = (MyApplication) getApplication();
        myApp.UrlApi = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlApi", "");
        myApp.UrlAgv = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlAgv", "");
        myApp.UrlMes = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlMes", "");
        myApp.UrlCloth = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlCloth", "");
        myApp.UrlWms = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlWms", "");
        myApp.UrlCut = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlCut", "");

        System.out.println("myApp.UrlApi："+myApp.UrlApi);
        System.out.println("myApp.UrlMes："+myApp.UrlMes);
        //查看链接数据库与版本更新
        //serviceUrl = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlMes", "http://121.229.24.37:8070");
        serviceUrl = (String) SharedPreferenceUtils.getData(sharedPreferences, "UrlMes", "");

        edLoginEdtId.setText((String)SharedPreferenceUtils.getData(sharedPreferences,"LoginUserNo",""));
        checkNetTimer();


        progressDialog=new ProgressDialog(this);
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {

    }


    @OnClick({R.id.sw,R.id.tv_login,R.id.iv_setting})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_login:
                if (TextUtils.isEmpty(myApp.UrlApi)){
                    Toaster.showLong(LoginActivity.this, "请先填写MES地址");
                    return;
                }
                if (!TextUtils.isEmpty(myApp.UrlMes)) {
                    String name = edLoginEdtId.getText().toString().trim();
                    String pwd = edLoginEdtPwd.getText().toString().trim();
                    if (!TextUtils.isEmpty(name)) {
                        if (!TextUtils.isEmpty(pwd)) {
                            if (progressDialog!=null){
                                progressDialog.show();
                            }
                            loginCheck(name, pwd);
                        } else {
                            Toaster.showLong(LoginActivity.this, "请填写密码");
                        }
                    } else {
                        Toaster.showLong(LoginActivity.this, "请填写用户名");
                    }
                } else {
                    Toaster.showLong(LoginActivity.this, "请设置MES地址");
                }
                break;
            case R.id.sw:
                if (isShow){
                    isShow=false;
                    edLoginEdtPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    aSwitch.setBackgroundResource(R.mipmap.yichang);
                }else {
                    edLoginEdtPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    isShow=true;
                    aSwitch.setBackgroundResource(R.mipmap.xianshi);
                }
                break;
            case R.id.iv_setting:
                startActivity(new Intent(LoginActivity.this, IPSettingActivity.class));
                break;
        }

    }

    //升级功能start

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            InstallUtils.installAPK(this, apkpath);
        }
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    //登陆校验;
    private void loginCheck(String name, String pwd) {
        // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
        pwd = new String(Base64.encode(pwd.getBytes(), Base64.DEFAULT));
        Log.i("Test", "tmpPassword>>>" + name);
        //组织WebService地址;
        String sqlComm="EXEC AGV_Basic_LoginCheck @UserNo='" + name + "',@PassWord='"+ pwd.replaceAll("\r|\n", "")+"'";
//        String sqlComm = "EXEC  @UserNo='" + name + "',@PassWord='" + pwd.replaceAll("\r|\n", "") + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlComm);
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    if (progressDialog!=null){
                        progressDialog.dismiss();
                    }
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("LoginCheck") == true) {
                            loginJSONArray = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_LoginCheckOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //返回的登陆信息;
                    }else {
                        Message msg = new Message();
                        msg.what = MSG_ERROR;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    e.printStackTrace();
                    System.out.print(e.toString());
                }

            }

        };
        new Thread(run).start();

    }

    //登陆成功
    private void loginOK() {
        //保存配置文件
        System.out.println(TAG + ":Login OK");
        Toaster.showLong(LoginActivity.this, "Login OK");
        //隐藏键盘
        hideIM(edLoginEdtPwd);
        new Thread() {
            public void run() {
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        //跳转前关闭键盘
        Intent mainActivity = new Intent(LoginActivity.this, MainActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
//        paramBundle.putString("LoginUserNo", curLoginUserNo);
//        paramBundle.putString("LoginUser", curLoginUser);
//        paramBundle.putString("LoginTime", curLoginTime);
//        paramBundle.putString("serviceUrl", serviceUrl);
//        paramBundle.putString("serviceUrlExt", serviceUrlExt);
//        paramBundle.putString("UserPower",curUserPower);
        mainActivity.putExtras(paramBundle);
        //启动主界面;
        startActivity(mainActivity);

    }

    //启动定时器;
    private void checkNetTimer() {
        if (netTimer == null) {
            netTimer = new Timer();
            System.out.println("onCreate timer---------------------------------2.1");
            //定时任务;
            if (netTimeTask == null) {
                netTimeTask = new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = MSG_CheckNetWork;
                        handler.sendMessage(message);
                    }
                };
            }
            System.out.println("onCreate timer---------------------------------2.2");
            netTimer.schedule(netTimeTask, 1000, 1000);
        }
    }

    //停止计时器;
    private void stopCheckNetTimer() {
        if (netTimer != null) {
            netTimer.cancel();
            netTimer = null;
        }
        if (netTimeTask != null) {
            netTimeTask.cancel();
            netTimeTask = null;
        }
        System.out.println("startTimer five---------------------------------Start");
    }

    //从网络获取版本升级文件
    public void CheckWebUpdate(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("serviceUrl", serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String, Object>, Void, String>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign = false;
                String serviceUrl = (String) params[0].get("serviceUrl");
                Log.d("GetWebUpdateFile", "文件接收A:---" + serviceUrl);

                ParseXmlService service = new ParseXmlService();
                InputStream inStream = null;
                try {
                    inStream = new URL(serviceUrl).openStream();
                    mHashMap = service.parseXml(inStream);
                    Log.e(TAG, "版本文件获取成功....");
                    return "OK";
                } catch (IOException e) {
                    ErrSign = true;
                    e.printStackTrace();
                } catch (Exception e) {
                    ErrSign = true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign == true) Log.d("TAG", "获取服务器配置文件异常,错误异常抛出！");
                return "NO";

            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr == null) || (rtnstr == "NO")) {
                    Toaster.showLong(LoginActivity.this, "版本更新文件下载错误");
                    return;
                }
                //这部分主要用于UI更新;
                Log.d("msg", "文件获取成功..");
                //判断版本是否相同;
                if (null != mHashMap) {
                    try {
                        int serviceCode = Integer.valueOf(mHashMap.get("version"));
                        String hintInfo = mHashMap.get("hint");
                        if (hintInfo == null) hintInfo = "1.更新已知Bug;";
                        Log.e(TAG, "hintInfo:" + hintInfo);
                        Log.e(TAG, "最新版本为" + serviceCode + "--------------------------------------------------");
                        // 版本判断
                        // 获取当前软件版本
                        int versionCode = getVersionCode(getApplication());
                        Log.e(TAG, "当前版本为" + versionCode + "--------------------------------------------------");
                        if (serviceCode > versionCode) {
                            Log.e(TAG, "准备显示升级提示对话框--------------------------------------------------");
                            // 显示提示对话框
                            showUpdate(hintInfo);
                        } else {
                            Toaster.showLong(LoginActivity.this, "版本已是最新版");
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage());
                    }
                }

            }
        }.execute(params);

    }


    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;

        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }

        return versionCode;
    }


    //显示升级任务
    private void showUpdate(String hintInfo) {
        int deviationX = 410, deviationY = 430;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        //创建并初始化完成
        //创建并初始化完成
        if (popupWindow == null) {
            popupWindow = new PopupWindow(this);
            popupWindow.setWidth(dm.widthPixels);
            popupWindow.setHeight(dm.heightPixels);
        }
        //取视图
        View popView = LayoutInflater.from(this).inflate(R.layout.softupdate, null);
        TextView txt_hintInfo = popView.findViewById(R.id.txt_hintInfo);
        TextView txt_BuildVer = popView.findViewById(R.id.txt_BuildVer);
        txt_BuildVer.setText("Build Ver:" + Build.VERSION.CODENAME);
        TextView txt_FilePath = popView.findViewById(R.id.txt_FilePath);
        apkpath = getFilePath(this) + File.separator + apkname;
        txt_FilePath.setText(apkpath);

        String[] strings = hintInfo.split(";");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            if (builder.length() > 0) builder.append("\r\n");
            builder.append(strings[i]);
        }
        txt_hintInfo.setText(builder.toString());
        btn_update = popView.findViewById(R.id.btn_update);
        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //下载最新程序
                progress_update.setVisibility(View.VISIBLE);
                txt_update.setVisibility(View.VISIBLE);
                btn_update.setVisibility(View.GONE);
                if (mHashMap == null || mHashMap.isEmpty()) {
                    Toaster.showLong(LoginActivity.this, "链接失效，请稍后再试");
                    popupWindow.dismiss();
                    return;
                }
                String appUrl = mHashMap.get("url");
                String appName = mHashMap.get("name");
                Log.e(TAG, "appUrl:" + appUrl + " appName:" + appName);
                //downloadAPK(appUrl, appName);
                downApkFromHttp(appUrl, appName);
            }
        });
        btn_update.requestFocus();
        txt_update = popView.findViewById(R.id.txt_update);
        txt_update.setVisibility(View.GONE);
        progress_update = popView.findViewById(R.id.progress_update);
        progress_update.setProgress(0);
        progress_update.setVisibility(View.GONE);
        txt_SoftVer2 = popView.findViewById(R.id.txt_SoftVer2);
        try {
            txt_SoftVer2.setText(this.getVersionName().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        popView.findViewById(R.id.img_update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //显示视图
        popupWindow.setContentView(popView);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x3F000000));//全透明背景
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(tvLogin, Gravity.CENTER, 0, 0);
    }


    //获取软件版本;
    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    private void downApkFromHttp(String fileUrl, String fileName) {
        apkname = fileName;
        //设置下载的路径
        String filePath = getFilePath(this);
        //String filePath=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        //delete(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/"+apkname);
        //apkpath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/"+apkname;
        FileUtils.delete(filePath + File.separator + apkname);
        apkpath = filePath + File.separator + apkname;
        new DownLoad().execute(fileUrl, fileName);
    }

    public class DownLoad extends AsyncTask<String, Integer, String> {
        //在执行实际的后台操作前被UI Thread调用
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //准备下载前的初始进度
            progress_update.setProgress(0);
        }

        //在onPreExecute执行，该方法运行在后台线程中
        @Override
        protected String doInBackground(String... params) {
            try {
                int prSize = 0, curLen = 0;
                URL url = new URL(params[0]);
                String fileName = params[1];
                //获取连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //获取下载文件的大小
                contentLen = connection.getContentLength();
                //根据下载文件大小设置进度条最大值（使用标记区别实时进度更新）
                publishProgress(PROGRESS_MAX, contentLen);
                //循环下载（边读取边存入）
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new
                        File(apkpath)));
                int len = -1;
                byte[] bytes = new byte[1024];
                while ((len = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                    bos.flush();
                    curLen += len;
                    if (curLen > (prSize + 256)) {
                        prSize = curLen;
                        //实时更新下载进度（使用标记区别最大值）
                        publishProgress(UPDATE, len);
                        //演示下载的图片太小，网速太快，休眠300毫秒，方便大家观察
                        //Thread.sleep(1);
                    }

                }
                bos.close();
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
            return "OK";
        }

        //在publishProgress被调用后，UI thread会调用这个方法
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            switch (values[0]) {
                case PROGRESS_MAX:
                    progress_update.setMax(values[1]);
                    break;
                case UPDATE:
                    progress_update.incrementProgressBy(values[1]);
                    //获取下载进度百分比并更新textview
                    int i = (progress_update.getProgress() * 100) / contentLen;
                    txt_update.setText("下载进度为：" + i + "%");
                    break;
            }
        }

        //doInBackground方法执行完后被UI thread执行
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equals("OK")) {
                progress_update.setVisibility(View.GONE);
                txt_update.setText("下载成功准备安装");
                //兼容8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        Uri packageUri = Uri.parse("package:" + getPackageName());
                        //注意这个是8.0新API
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivityForResult(intent, 10086);
                        return;
                    }
                }
                InstallUtils.installAPK(LoginActivity.this, apkpath);
            } else {
                txt_update.setText("下载失败");
                //下载最新程序
                progress_update.setVisibility(View.GONE);
                txt_update.setVisibility(View.GONE);
                btn_update.setVisibility(View.VISIBLE);
                btn_update.setText("下载失败,请重试");
                Toaster.showLong(LoginActivity.this, "下载失败,请重试");
            }
        }
    }


}
